#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<glob.h>
#include<unistd.h>
#define PATHSIZE 1024
static int is_loop(const char *name)
{
	char *newname;

	newname=strrchr(name,'/');
	if(newname==NULL)
		return -1;
	if(strcmp(newname+1,".")==0||strcmp(newname+1,"..")==0)
	{
		return 0;
	}
	return 1;
}


static int64_t mydu(const char *path)
{
	struct stat statresult;
	glob_t glob_st;
	char newpath[PATHSIZE]={0};
	int64_t sum;
	int i,err;
	if(lstat(path,&statresult)<0)
	{
		perror("lstat()");
		return 0;
	}
	if(!S_ISDIR(statresult.st_mode))
	{
		return statresult.st_blocks;
	}
	sum=statresult.st_blocks;
	strncpy(newpath,path,PATHSIZE);
	strncat(newpath,"/*",PATHSIZE-1);
	err=glob(newpath,0,NULL,&glob_st);
	if(err)
	{
		perror("glob");
		return 0;
	}
	strncpy(newpath,path,PATHSIZE);
	strncat(newpath,"/.*",PATHSIZE-1);
	glob(newpath,GLOB_APPEND,NULL,&glob_st);
	for(i=0;i<glob_st.gl_pathc;i++)
	{
		if(is_loop(glob_st.gl_pathv[i]))
		{
			sum+= mydu(glob_st.gl_pathv[i]);
		}
	}
	globfree(&glob_st);
	printf("%ldK   \t%s\n",sum/2,path);
	return sum;
}


int main(int argc,char **argv)
{

		if(argc<2)
		{
			perror("input error");
			return -1;
		}
		printf("size=%ldK\t%s\n",mydu(argv[1])/2,argv[1]);
		return 0;
}
